package com.smart.web.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.smart.consts.AppInteractiveState;
import com.smart.consts.AppStatusData;
import com.smart.dao.Page;
import com.smart.dao.PageRequest;
import com.smart.model.Loan;
import com.smart.model.LoanCond;
import com.smart.model.User;
import com.smart.model.base.JsonModel;
import com.smart.util.JsonUtil;

@Controller
public class LoanController extends BaseController{
	@RequestMapping(value = "admin/loan/list")
	public String listLoan(PageRequest pageRequest, Model model){
		Page<Loan> page = loanService.findAll(pageRequest);
		model.addAttribute("page", page);
		return "admin/loan/list";
	}
	
	@RequestMapping(value = "admin/loan/edit", method=RequestMethod.GET)
	public String preEditLoan(Long id, Model model) {
		if(id!=null){
			Loan loan = loanService.findOne(id);
			model.addAttribute("obj", loan);
		}
		return "admin/loan/edit";
	}
	
	@RequestMapping(value = "admin/loan/edit", method=RequestMethod.POST)
	public String editLoan(Loan form, Model model, RedirectAttributes ra) {
		loanService.save(form);
		model.addAttribute("obj", form);
		setSuccessMsg(ra);
		return "redirect:edit?id=" + form.getId();
	}
	
	@RequestMapping(value = "admin/loan/delete", method=RequestMethod.GET)
	public @ResponseBody String deleteLoan(Long id) {
		loanService.delete(id);
		return "OK";
	}
	
	@RequestMapping(value = "entry")
	public String entry(){
		return "entry";
	}
	
	@RequestMapping(value = "entry1")
	public String entry1(){
		return "entry1";
	}
	
	@RequestMapping(value = "entry2")
	public String entry2(){
		return "entry2";
	}
	
	@RequestMapping(value = "entry6")
	public String entry6(){
		return "entry6";
	}
	
	@RequestMapping(value = "list")
	public String list(){
		return "list";
	}
	
	@RequestMapping(value = "loan/query")
	public @ResponseBody List<Loan> query(LoanCond cond) {
		cond.addOrderByAsc("sort");
		return loanService.find(cond);
	}
	
	@RequestMapping(value = "loan/queryJsonp")
	public void queryJsonp(LoanCond cond, String callback, HttpServletResponse response) 
			throws UnsupportedEncodingException, IOException {
		cond.addOrderByAsc("sort");
		List<Loan> list = loanService.find(cond);
		String json = JsonUtil.collection2json(list);
		String result = callback + "(" + json + ")";
		response.getOutputStream().write(result.getBytes("utf-8"));
		response.getOutputStream().flush();
	}
}
